package com.oracle.zebrafreelytraveling.ui.service;

import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.oracle.zebrafreelytraveling.data.model.Message;
import com.oracle.zebrafreelytraveling.ui.ChatActivity;
import com.oracle.zebrafreelytraveling.utils.constant.Constant;
import com.oracle.zebrafreelytraveling.utils.GsonUtil;
import com.oracle.zebrafreelytraveling.utils.UserUtil;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by yydcnjjw on 2017/7/24.
 */

public class WebSocketService extends Service {

//    //接收的消息为当前界面的消息
//    private static final int RECEVICE_TYPE_ACTIVE = 1;
//
//    //接收的消息不是当前界面的消息
//    private static final int RECEVICE_TYPE_SLEEP = 2;

    private static Map<String, String> map;
    private static final String USER_ID = "userId";

    private WebSocketClient socket;

    private ChatBinder chatBinder = new ChatBinder();

    private onMessageListener listener;

    //聊天类型
    private String chatType;
    //id
    private int circleOrFriendId;

    private Disposable mDisposable;

    public WebSocketService() throws URISyntaxException {
    }

    @Override
    public void onCreate() {
        try {
            initWebSocket();
        } catch (Exception e) {
            e.printStackTrace();
        }

        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            circleOrFriendId = intent.getIntExtra(ChatActivity.ID, -1);
            chatType = intent.getStringExtra(ChatActivity.CHAT_TYPE);
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        if (socket.isConnecting()) {
            socket.close();
        }
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return chatBinder;
    }

    private void initWebSocket() throws Exception {
        Map<String, String> map = new HashMap<>();
        //放入header
        map.put(USER_ID, getUserId());
        URI uri = new URI(Constant.WEB_SOCKET_CHAT_RING);
        Observable.create(e -> {
            try {
                socket = new WebSocketClient(uri, new Draft_6455(), map, 100000) {
                    @Override
                    public void onOpen(ServerHandshake handshakedata) {
                        Log.d("websocket", "onopen");
                    }

                    @Override
                    public void onMessage(String message) {
                        e.onNext(message);
                    }

                    @Override
                    public void onClose(int code, String reason, boolean remote) {
                        Log.d("websocket", "onClose: " + code + " " + reason);
                        try {
                            initWebSocket();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Exception ex) {
                        Log.d("websocket", ex.getMessage());
                        try {
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                };
            } catch (Exception ex) {
                ex.getMessage();
            }
            socket.connectBlocking();
        }).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Object>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(@NonNull Object o) {
                        if (listener != null) {
                            judgeMessageType(o.toString());
                        } else {
                            Log.d("listener", "listener is null");
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 获取数据库用户
     *
     * @return
     */
    private String getUserId() {
        return UserUtil.getUserInfoFromSP().getUserId()+"";
    }

    public class ChatBinder extends Binder {

        public void sendMessage(String message, String type, int userId) {
            if (socket.isOpen()) {
                socket.send(message);
            }

        }
        public void getBindActivityInfo(Activity activity) {
            try {
                listener = (onMessageListener) activity;
            } catch (ClassCastException e) {
                throw new ClassCastException(this.toString()
                        + " 必须继承OnMessageListener");
            }
        }

    }

    public interface onMessageListener {
        //如果用户当前状态是在聊天界面并且 接收的消息也是
        //当前群组或者好友的消息则调用这个函数
        void getReceiveMessageToActive(Message message);
    }


    //如果用户当前状态是在聊天界面并且接收的消息也是
    //当前群组或者好友的消息则返回 RECEVICE_TYPE_ACTIVE
    //如果用户不在当前页面或者消息不是当前页面的消息
    //返回RECEVICE_TYPE_SLEEP
    private void judgeMessageType(String message) {
        Message msg = GsonUtil.getInstance().fromJson(message, Message.class);
        Log.d("message", message);
        int sendId = msg.getSendId();
        if (sendId == circleOrFriendId){
            sendNotification(msg);
        } else {
            listener.getReceiveMessageToActive(msg);
        }
    }

    /**
     * 当用户关闭应用是如果有消息则发送通知
     * 通过读取数据库id显示相关消息
     */
    private void sendNotification(Message message) {
//        Notification notification = new Notification(R.drawable.ic_launcher,
//                "有通知到来", System.currentTimeMillis());
//        Intent notificationIntent = new Intent(this, MainActivity.class);
//        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
//                notificationIntent, 0);
//        notification.setLatestEventInfo(this, "这是通知的标题", "这是通知的内容",
//                pendingIntent);
//        startForeground(1, notification);
//        Log.d(TAG, "onCreate() executed");
    }
}
